<template>
    <div class="container">
        <Swipe></Swipe>
        <div class="searchbox">
            <Search></Search>
        </div>
        <div class="button-container">
            <router-link :to="{ path: '/homeviewtwo/1' }">
                <Button>环保政策与法规</Button>
            </router-link>
            <router-link :to="{ path: '/homeviewtwo/2' }">
                <Button>环境污染与治理</Button>
            </router-link>
            <router-link :to="{ path: '/homeviewtwo/3' }">
                <Button>生态保护生物多样性</Button>
            </router-link>
            <router-link :to="{ path: '/homeviewtwo/4' }">
                <Button>绿色生活与节能减排</Button>
            </router-link>
            <router-link :to="{ path: '/homeviewtwo/5' }">
                <Button>科技创新与环保应用</Button>
            </router-link>
            <router-link :to="{ path: '/homeviewtwo/6' }">
                <Button>环保教育与公益活动</Button>
            </router-link>
            <router-link :to="{ path: '/homeviewtwo/7' }">
                <Button>国际环保交流与合作</Button>
            </router-link>
            <router-link :to="{ path: '/homeviewtwo/8' }">
                <Button>环境热点与深度分析</Button>
            </router-link>
        </div>

        <van-divider content-position="left">热门精选</van-divider>
        <div class="content">
            <template v-for="(item, index) in items" :key="index">
                <router-link :to="`/item/${item.id}`"> <!-- 新增跳转链接 -->
                    <van-cell :title="item.title"></van-cell>
                    <img :src="item.thumb" alt="封面" class="png">
                    <van-cell :desc="item.desc"></van-cell>
                </router-link> <!-- 结束链接 -->
            </template>

            <!-- 添加加载提示 -->
            <div v-if="isLoading" class="loading">
                <van-loading type="spinner" size="24px">加载中...</van-loading>
            </div>
            <div v-if="!hasMore" class="no-more">没有更多数据了</div>
        </div>
        <div style="width: 100%; height: 1000px; background-color: #eee;"></div>
        <tabbar></tabbar>
    </div>
</template>

<script setup>
import Swipe from "../components/Swipe.vue"
import Search from "../components/Search.vue"
import Button from "../components/Button.vue"
import { ref, onMounted, onUnmounted } from 'vue'
import axios from 'axios'

const items = ref([])
const isLoading = ref(false)
const hasMore = ref(true)
const loadedIds = ref(new Set())

// 生成不重复ID（带重试限制）
const getRandomId = () => {
    let id, retry = 0
    const maxRetry = 50 // 最大重试次数

    do {
        id = Math.floor(Math.random() * 20) + 1
        if (retry++ > maxRetry) return null // 防止死循环
    } while (loadedIds.value.has(id))

    loadedIds.value.add(id)
    return id
}

// 核心加载逻辑
const loadMore = async () => {
    if (isLoading.value || !hasMore.value) return

    isLoading.value = true
    try {
        // 生成有效请求
        const validRequests = []
        for (let i = 0; i < 5; i++) {
            const id = getRandomId()
            if (id !== null) {
                validRequests.push(axios.get(`http://localhost:8080/api/item/${id}`))
            }
        }

        // 无有效ID时停止加载
        if (validRequests.length === 0) {
            hasMore.value = false
            return
        }

        // 处理请求结果
        const responses = await Promise.allSettled(validRequests)
        const newItems = responses
            .filter(r => r.status === 'fulfilled' && r.value.data.code === "0")
            .map(r => r.value.data.data)

        items.value.push(...newItems)

        // 停止加载条件（ID耗尽或没有新数据）
        if (loadedIds.value.size >= 18 || newItems.length === 0) {
            hasMore.value = false
        }
    } catch (error) {
        console.error('加载失败:', error)
        hasMore.value = false // 出错时停止加载
    } finally {
        isLoading.value = false
    }
}

// 滚动处理（带安全判断）
const handleScroll = () => {
    const doc = document.documentElement
    if (!doc) return

    const scrollThreshold = 100 // 恢复合理触发距离
    const { scrollTop, clientHeight, scrollHeight } = doc

    if (scrollTop + clientHeight >= scrollHeight - scrollThreshold) {
        loadMore()
    }
}

// 防抖优化
let debounceTimer
const debouncedScrollHandler = () => {
    clearTimeout(debounceTimer)
    debounceTimer = setTimeout(handleScroll, 200) // 增加防抖时间
}

// 初始化时重置状态
const resetState = () => {
    items.value = []
    loadedIds.value.clear()
    hasMore.value = true
}

onMounted(() => {
    resetState() // 关键修复：刷新时重置状态
    window.addEventListener('scroll', debouncedScrollHandler)
    loadMore()
})

onUnmounted(() => {
    window.removeEventListener('scroll', debouncedScrollHandler)
    clearTimeout(debounceTimer)
})
</script>

<style scoped>
.searchbox {
    margin-top: 10px;
}

.button-container {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
}

.container {
    padding: 2em;
}

.png {
    width: 100%;
    height: 140px;
}

.loading,
.no-more {
    text-align: center;
    padding: 16px;
    color: #969799;
}
</style>